// SIPManage.dart
import 'package:flutter/cupertino.dart';
import 'package:sip_sdk_flutter/entitys/sip_sdk_call_param.dart';
import 'package:sip_sdk_flutter/entitys/sip_sdk_config.dart';
import 'package:sip_sdk_flutter/entitys/sip_sdk_dtmf_info.dart';
import 'package:sip_sdk_flutter/entitys/sip_sdk_local_config.dart';
import 'package:sip_sdk_flutter/entitys/sip_sdk_media_config.dart';
import 'package:sip_sdk_flutter/entitys/sip_sdk_message.dart';
import 'package:sip_sdk_flutter/entitys/sip_sdk_registrar_config.dart';
import 'package:sip_sdk_flutter/entitys/sip_sdk_stun_config.dart';
import 'package:sip_sdk_flutter/entitys/sip_sdk_turn_config.dart';
import 'package:sip_sdk_flutter/sip_sdk_callbacks.dart';
import 'package:sip_sdk_flutter/sip_sdk_flutter.dart';


typedef OnCallState = void Function(String callUUID, int state);
typedef OnRegistrarState = void Function(int state);
typedef OnCameraStateChange = void Function(bool state);

class SIPListener {
  final OnCallState? onCallState;
  final OnRegistrarState? onRegistrarState;
  final OnCameraStateChange? onCameraStateChange;

  const SIPListener({
    this.onCallState,
    this.onRegistrarState,
    this.onCameraStateChange,
  });
}

abstract class MyListener {
  void onEvent(String data); // 抽象方法，相当于接口方法
  void onError(int code); // 可以定义多个
}

class SIPManage implements SIPSDKCallbacks {
  @override
  void onCameraStateChange(bool state) {
    for (final listener in List<SIPListener>.from(_listeners)) {
      listener.onCameraStateChange?.call(state);
    }
  }
  final List<SIPListener> _listeners = [];

  // 私有构造函数
  SIPManage._internal();

  // 设备模型
  String? _deviceModel;

  // 静态私有实例
  static final SIPManage _instance = SIPManage._internal();

  // 工厂构造函数返回单例
  factory SIPManage() => _instance;

  static late SipSdkFlutter _sipSdkFlutterPlugin;

  // 新增：记录是否已初始化
  static bool _isInitialized = false;

  // 还需要添加一个变量来跟踪注册状态
  int _registrationState = 0; // 0:未初始化, 1:注册中, 2:已注册, 3:注册失败

  static void initialize(String deviceModel) {
    // 如果已初始化，直接返回，避免重复执行
    if (_isInitialized) {
      return;
    }

    _instance._deviceModel = deviceModel;
    // 初始化插件
    _sipSdkFlutterPlugin = SipSdkFlutter();
    // 设置回调
    _sipSdkFlutterPlugin.setupCallbacks(_instance);
    // 初始化SDK
    initSDK();

    // 标记初始化完成
    _isInitialized = true;
  }

  // 新增：暴露初始化状态判断方法
  static bool isInitialized() {
    return _isInitialized;
  }

  // 在SIPManage类中添加
  bool getRegistrationStatus() {
    // 这里需要根据实际SDK提供的方法来检查注册状态
    // 示例中假设我们有一个方法可以获取注册状态
    return _registrationState == 200; // 2表示已注册
  }

  // 修改回调方法以更新注册状态
  @override
  void onRegistrarState(int state) {
    debugPrint("onRegistrarState: $state");
    _registrationState = state;
    // 可以在这里添加状态变化的通知逻辑
  }

  // 你可以继续在这里写你自己的方法：
  static void initSDK() {
    final config = SIPSDKConfig(
      baseUrl: "https://120.79.7.237",
      clientId: "1379018005584941056",
      clientSecret: "7489ed9e086e12ab45688c0caf4a7d2b",
      userAgent: 'JHCloud-flutter-1.0',
      mediaConfig: SIPSDKMediaConfig(),
      stunConfig: STUNConfig(
        servers: ["120.79.7.237:3478"],
        // servers: ["110.42.103.180:3478"],
        // servers: ["43.139.39.5:3478"],
        // servers: ["110.42.103.180:3478"],
        enableIPv6: false,
      ),
    );
    _sipSdkFlutterPlugin.initSDK(config);
  }

  void registrar() {
    final config = SIPSDKRegistrarConfig(
      // domain: "test.com",
      // username: "RM-1-1-1-1-1-1",
      // password: "123456",
      // transport: "tcp",
      // serverAddr: "43.160.204.96",
      // serverPort: 5060,
      // proxy: "43.160.204.96",
      // proxyPort: 5060,
      domain: "test.com",
      username: _instance._deviceModel,
      password: "1234",
      transport: "tcp",
      // serverAddr: "43.139.39.5",
      serverAddr: "110.42.103.180",
      serverPort: 5060,
      // proxy: "43.139.39.5",
      proxy: "110.42.103.180",
      proxyPort: 5060,
      enableStreamControl: false,
      streamElapsed: 0,
      startKeyframeCount: 120,
      startKeyframeInterval: 1000,
      turnConfig: SIPSDKTURNConfig(
        enable: false,
        server: "120.79.7.237:3478",
        realm: "120.79.7.237",
        username: "test",
        password: "test",
        // server: "110.42.103.180:3478",
        // realm: "110.42.103.180",
        // server: "43.139.39.5:3478",
        // realm: "flutter-webrtc",

        // username: "root",
        // password: "root",

        // server: "110.42.103.180:3478",
        // realm: "110.42.103.180",
        // username: "root",
        // password: "root",

      ),
      localConfig: SIPSDKLocalConfig(
        username: _instance._deviceModel,
        enableStreamControl: false,
        streamElapsed: 0,
        startKeyframeCount: 120,
        startKeyframeInterval: 1000,
      ),
    );

    print("23434444444");
    _sipSdkFlutterPlugin.registrar(config);
  }

  void unRegistrar() {
    _sipSdkFlutterPlugin.unRegistrar();
  }

  void call(String username, Map<String, String> headers) {
    _sipSdkFlutterPlugin.call(username, headers);
  }

  void callIP(String ip, Map<String, String> headers) {
    _sipSdkFlutterPlugin.callIP(ip, headers);
  }

  // 通常情况不用调用接听，因为被叫界面是原生代码
  void answer(int code, String callUUID) {
    _sipSdkFlutterPlugin.answer(code, callUUID);
  }

  // 通常情况不用调用发送Dtmf Info，因为被叫界面是原生代码
  void sendDtmfInfo(int type, String content, String callUUID) {
    _sipSdkFlutterPlugin.sendDtmfInfo(type, content, callUUID);
  }

  // 通常情况不用调用挂断，因为被叫界面是原生代码
  void hangup(int code, String callUUID) {
    _sipSdkFlutterPlugin.hangup(code, callUUID);
  }

  void sendMessage(String username, String content) {
    _sipSdkFlutterPlugin.sendMessage(username, content);
  }

  void sendMessageIP(String username, String content) {
    _sipSdkFlutterPlugin.sendMessageIP(username, content);
  }

  // 通常情况不用调用dump，这个主要用于调试
  void dump() {
    _sipSdkFlutterPlugin.dump();
  }

  @override
  void onInitCompleted(int state, String message) {
    debugPrint("onInitCompleted: $state    $message");
    // 初始化成功，注册
    if (state == 0) {
      registrar();
    }
  }

  @override
  void onStopCompleted() {
    debugPrint("onStopCompleted");
  }

  @override
  void onDtmfInfo(SIPSDKDtmfInfo dtmfInfo) {
    debugPrint("onDtmfInfo: ${dtmfInfo.toString()}");
  }

  @override
  void onMessage(SIPSDKMessage message) {
    debugPrint("onDtmfInfo: ${message.toString()}");
  }

  @override
  void onMessageState(int state, SIPSDKMessage message) {
    debugPrint("onDtmfInfo: $state:${message.toString()}");
  }

  @override
  void onCallState(String callUUID, int state) {
    debugPrint("onCallState: $callUUID:$state");
  }

  @override
  void onIncomingCall(SIPSDKCallParam callParam) {
    debugPrint("onIncomingCall: ${callParam.toString()}");
  }

  @override
  void onExpireWarning(DateTime expireTime, DateTime currentTime) {
    final expireStr = expireTime.toLocal().toString();
    final currentStr = currentTime.toLocal().toString();
    debugPrint(
      'License will expire at: $expireStr, current time is: $currentStr',
    );
  }
}